package handler

import (
	"compress/common"

	"encoding/json"
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"math"
	"net/http"
	"time"
)

type M struct {
	Action string      `json:"action,omitempty"`
	Data   map[string]interface{} `json:"data,omitempty"`
}

func (m M) AddMsgQueue(messageType int, r common.WsRes)  {

	SendMessageData = append(SendMessageData,MessageData{
		messageType: messageType,
		data:r.ToJson(),
	});
}

var addr = flag.String("addr", "localhost:8080", "http service address")

var upgrader = websocket.Upgrader{
	CheckOrigin : checkOrigin,
} // use default options

//不检查 origin
func checkOrigin (r *http.Request) bool {
	return true
}

//http 请求拦截器
func HTTPInterceptor(h http.HandlerFunc)  http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin","*")
		h(w, r)
	})
}


func Echo(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	go sendQueue(c)
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		fmt.Println(mt)
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("接收消息: %s", message)
		go msgHandle(c,mt,message)
		//err = c.WriteMessage(mt, message)
	}
}


func msgHandle(c *websocket.Conn,mt int,msg []byte) {
	message,err := MsgToMap(msg)
	if err != nil {
		return
	}

	switch message.Action {
		case "imgs":
			go GetLocationImgs(mt,message)
		case "compress" :
			go CompressImgs(mt,msg,message)
		case "config" :
			go GetConfig(mt,message);
		case "config.update" :
			go UpdateConfig(mt,message);
		case "ping" :
			go Pong(mt,message);
	}
}

var SendMessageData []MessageData;

type MessageData struct {
	messageType int
	data []byte
}

func Pong(mt int,msg M)  {
	AddMsgQueue(mt,common.WsRes{
		Code:      common.SUCCESS,
		Data:      nil,
		ErrorCode: 0,
		Action:    msg.Action,
		Msg:       "pong",
	})
}

func sendQueue(c *websocket.Conn) {
	for  {
		length := len(SendMessageData);
		if length < 1  {
			time.Sleep(1*time.Second);
			continue;
		}

		for k,messData := range SendMessageData {
			log.Println(k,"发送给",messData.messageType,string(messData.data),)
			err := c.WriteMessage(messData.messageType,messData.data)
			if err != nil {
				log.Println(err)
				return;
			}else{
				log.Println("SEND SUCCESS")
			}
		}

		n := int(math.Min(float64(length),float64(len(SendMessageData))))
		SendMessageData = SendMessageData[n:]
	}
}

func AddMsgQueue(messageType int, r common.WsRes)  {

	SendMessageData = append(SendMessageData,MessageData{
		messageType: messageType,
		data:r.ToJson(),
	});
}









func MsgToMap(msg []byte) (M,error) {
	data := M{}
	err := json.Unmarshal(msg, &data)
	if err != nil {
		log.Println("msg",err)
		return data,err
	}
	return data,err
}
